<?php


namespace app\admin\controller;


use app\admin\service\RbacService;
use app\common\controller\CommonController;
use app\common\exception\ParameterFailedException;
use app\common\model\ArticleModel;
use app\common\model\MediaModel;
use app\common\service\Lang;
use app\common\validate\ArticleValidate;
use app\common\validate\RCBCValidate;
use think\facade\Db;

class ArticleController extends CommonController
{
    public function getArticleList()
    {
        $articleListModel = (new ArticleModel())->select();
        return retJson(Lang::GETDone, $articleListModel->toArray());
    }

    public function postArticle()
    {
        $permissionsInfo = RbacService::checkPermissions('admin');
        $params          = self::getParam(['article_title', 'article_content']);
        (new ArticleValidate())->goCheck(__FUNCTION__, $params);

        $articleModel          = new ArticleModel();
        $articleModel->title   = $params['article_title'];
        $articleModel->content = $params['article_content'];
        $articleModel->user_id = $permissionsInfo['user_id'];
        $articleModel->save();

        return retJson(Lang::POSTDone);

    }

    public function putArticle()
    {
        $permissionsInfo = RbacService::checkPermissions('admin');
        $params          = self::getParam(['article_id', 'article_title', 'article_content']);
        (new ArticleValidate())->goCheck(__FUNCTION__, $params);
        Db::startTrans();
        try {
            $articleModel = (new ArticleModel())->where('id', $params['article_id'])->find();
            if (!$articleModel) {
                throw new ParameterFailedException(['msg' => '数据不存在']);
            }
            $articleModel->title   = $params['article_title'];
            $articleModel->content = $params['article_content'];
            $articleModel->save();

            Db::commit();
            return retJson(Lang::PUTDone);
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    public function deleteArticle()
    {
        return retJson(Lang::DELETEDone);

    }
}
